#include <stdio.h>

#include <stdlib.h>

#include <sys/types.h>

#include <unistd.h>

#include <sys/wait.h>



int main(void)

{

    int count = 1;

    pid_t childpid; 

    


    //vfork没有分配新的内存空间,而是把父进程的空间和数据都共享给子进程,这个时候子进程在堆栈上的操作都会影响到父进程的堆栈
    childpid = vfork(); /* child shares parent’s address space */

    if (childpid < 0) {

        perror("fork()");

        return EXIT_FAILURE;

    }

    else /* vfork() returns 2 values: 0 for child pro and childpid for parent pro */

        if (childpid == 0) { /* This is child pro, parent hung up until child exit ...  */

            //子进程的环境

            count++;

            printf("Child pro pid = %d, count = %d (addr = %p)\n", getpid(), count, &count); 

            printf("Child taking a nap ...\n");

            //这个时候尽管子进程被挂起,父进程还是处于阻塞状态,必须得等子进程执行完之后才能退出
            sleep(5);

            printf("Child waking up!\n");

            //return 0; /* or exec(0); "return" will cause stack smashing */
            //子进程退出
            //如果return的话会造成stack smashing
            _exit(0);

        }

        else { /* This is parent pro, start when the vforked child finished */

            printf("Parent pro pid = %d, child pid = %d, count = %d (addr = %p)\n", getpid(), childpid, count, &count);

            wait(0); /* not waitting this vforked child terminated*/

        }
        
        //由于子进程的退出,只有父进程到达了testing point

    printf("Testing point by %d\n", getpid()); /* executed by parent pro only */

    return EXIT_SUCCESS;

}

